package logging

import (
	"Hypnos-Soundcore/constants"
	"encoding/json"
	"os"
	"sync"
)

var (
	loggingTool *LogTool
	once        sync.Once
)

// Config .
type Config struct {
	Enable       bool   `json:"enable" yaml:"enable"`
	Area         string `json:"area" yaml:"area"`
	FileName     string `json:"file_name" yaml:"file_name"`         // app和基站上报日志文件
	FileApi      string `json:"file_api" yaml:"file_api"`           // api接口日志文件
	FileCommerce string `json:"file_commerce" yaml:"file_commerce"` // 商城日志文件
	FileTracking string `json:"file_tracking" yaml:"file_tracking"` // app埋点数据
	HostName     string `json:"hostname" yaml:"hostname"`
}

// LogTool .
type LogTool struct {
	globalConf Config
}

// Enable .
func Enable() bool {
	//return GetLoggingTool().globalConf.Enable
	return true
}

// SetConfig .
func SetConfig(conf Config) {
	GetLoggingTool().SetConfig(conf)
}

// GetLoggingTool .
func GetLoggingTool() *LogTool {
	once.Do(func() {
		loggingTool = &LogTool{}
	})
	return loggingTool
}

// SetConfig .
func (l *LogTool) SetConfig(conf Config) {
	l.globalConf = conf
	l.globalConf.HostName = os.Getenv("HOSTNAME")
}

// GetConfig .
func (l *LogTool) GetConfig() Config {
	return l.globalConf
}

func LogTracing(eventName string, eventType string, url string, requestParam, responseParam interface{}, extraParam map[string]string, latency int64, err error) {
	param := make(map[string]interface{})
	param[constants.ParamPath] = url
	param[constants.ParamEventType] = eventType
	param[constants.ParamLatency] = latency
	if requestParam != nil {
		if requestByte, jsonErr := json.Marshal(requestParam); jsonErr == nil {
			param[constants.ParamRequestParam] = string(requestByte)
		}
	}
	if responseParam != nil {
		if responseByte, jsonErr := json.Marshal(responseParam); jsonErr == nil {
			param[constants.ParamResponseParam] = string(responseByte)
		}
	}
	if len(extraParam) != 0 {
		if requestHeaderByte, jsonErr := json.Marshal(extraParam); jsonErr == nil {
			param[constants.ParamExtraParam] = string(requestHeaderByte)
		}
	}
	SaveLogEventToFile(eventName, param, err)
}
